/**********************************************************************************
Program:       Real-time Weather Report

License:       GNU/GPL version 3

File:          UserDefinedCities.cs

Description:   读取 UserData.cfg（不存在则创建），存储城市名称到 List 结构

Author:        Guangyu Liu （lgy0417@gmail.com）

Environment:   .NET Framework v2.0 or later version

Usage/Example: README_chs.txt

Last Modified: 2010.08.30

***********************************************************************************/


using System;
using System.IO;
using System.Collections.Generic;

namespace WeatherInfo
{	
	public class CitiesByUser
	{
		private List<SingleCity> _originalist;   // 初始化之后保持不变，用于在程序退出时判断列表是否变化
		private List<SingleCity> _cityList;      // 初始时与 _originalist 相同，传入主程序供用户修改
		private static readonly string _dataFilePath = @"UserData.cfg";
		
		#region Public Members
		
		public CitiesByUser()
		{
			_originalist = new List<SingleCity>();
			if (!File.Exists(_dataFilePath))
			{
				SingleCity bj = new SingleCity(2, 0, 0, 101010100, "北京市区");
				SingleCity tj = new SingleCity(27, 0, 10, 101030100, "天津市区");
				SingleCity sh = new SingleCity(24, 0, 8, 101020100, "上海市区");
				SingleCity cq = new SingleCity(33, 0, 33, 101040100, "重庆市区");
				_originalist.AddRange(new SingleCity[] {bj, tj, sh, cq});
			}
			else
			{
				using (BinaryReader br = new BinaryReader(File.Open(_dataFilePath, FileMode.Open)))
				{
					int count = br.ReadInt32();      // 读入城市个数
					int p, c, t, i;
					string n;
					for (int j = 0; j < count; j++)
					{
						p = br.ReadInt32();
						c = br.ReadInt32();
						t = br.ReadInt32();
						i = br.ReadInt32();
						n = br.ReadString();
						_originalist.Add(new SingleCity(p, c, t, i, n));
					}
				}
			}
			_cityList = new List<SingleCity>();
			foreach (SingleCity i in _originalist)
				_cityList.Add(i);
		}
	
		public List<SingleCity> CityList
		{
			get { return _cityList; }
			set { _cityList = value; }    // 当用户在 ListBox 中编辑了自定义城市，并确定修改后，更新此内容
		}
		
		public List<SingleCity> OriginalList
		{
			get { return _originalist; }
		}
		
		public void Save()
		{
			using (BinaryWriter bw = new BinaryWriter(File.Open(_dataFilePath, FileMode.Create)))
			{
				bw.Write(_cityList.Count);
				for (int i = 0; i < _cityList.Count; i++)
					BinaryWriteStruct(bw, _cityList[i]);
			}
		}
		
		public string[] GetCityNameRange()   // 用于 combobox
		{
			string[] cityNamaRange = new string[_cityList.Count];
			for (int i = 0; i < _cityList.Count; i++)
				cityNamaRange[i] = _cityList[i].Name;
			return cityNamaRange;
		}
		
		#endregion
		
		#region Private Members
		
		private void BinaryWriteStruct(BinaryWriter bw, SingleCity sc)
		{
			bw.Write(sc.IndexOfProvince);
			bw.Write(sc.IndexOfCity);
			bw.Write(sc.IndexOfTown);
			bw.Write(sc.CityID);
			bw.Write(sc.Name);
		}
		
		#endregion
	}
}
